<?php
    include "WebClient.class.php";
    include "WebFormClient.class.php";
    require_once(dirname(dirname(__FILE__))."/config/config.inc.php");
	require_once(dirname(dirname(__FILE__))."/images.inc.php");
    
    $client = new WebFormClient();
    date_default_timezone_set('Asia/Bangkok');
    $client->setLogPrefix(dirname(dirname(__FILE__)).'/log/'.date("Y-m-d H-i-s O", time()));
    $base_url = 'http://www.yes24.vn/';
    $oriflame_url = '/Display/Brand/Brand3rd.aspx?FCategoryNo=444160&SCategoryNo=&TCategoryNo=451820';
    $client->get($base_url.$oriflame_url);
    
    $doc = new DOMDocument();
	@$doc->loadHTML($client->getBody());
	$xpath = new DOMXpath($doc);

	// get all category urls
	$nodes = $xpath->query('//table[@id="ctl00_ContentPlaceHolder2_ctl01_dlSubBrand"]/tr');
	$categories = array();
	$index = 3;
	$sql = "SELECT id_lang FROM "._DB_PREFIX_."lang";
	$results = Db::getInstance()->ExecuteS($sql);
	$ids_lang = array();
	foreach ($results as $row)
	   $ids_lang[] = $row['id_lang'];

	foreach ($nodes as $node) {
	    $as = $xpath->query('td/a', $node);
	    foreach ($as as $a) {
	        foreach ($a->attributes as $name => $attr_node)
	            if ($name == 'href') {
	                preg_match('#DCategoryNo=([0-9]*)#', $attr_node->value, $match);
	                $categories[$match[1]]['url'] = $attr_node->value;					
	            }
	                
	        // TODO: do request to find vnese lang id
	        $category = new Category(null, 6);
	        $name = str_replace('/', '-', $a->nodeValue);
	        if (!$category->searchByName(6, $name)) {
	            $category->name = pSQL($name);
				$category->link_rewrite = pSQL(get_link($category->name));
    	        $category->active = 1;
    	        $category->id_parent = 1;
    	        $category->level_depth = 1;
				
    	        $category->save();
				
                foreach ($ids_lang as $index => $value) {
    	            Db::getInstance()->autoExecute(
    	                _DB_PREFIX_.'category_lang',
    	                array(
    	                    'id_category'     => $category->id,
    	                    'name' => $category->name,
							'link_rewrite' => get_link($category->name),
    	                    'id_lang' => (int)$value), 'INSERT');
    	        }
				
				$categories[$match[1]]['prestashop_id'] = $category->id;
	        } 
			else {
				$category_arr = $category->searchByName(6, $name);
				$categories[$match[1]]['prestashop_id'] = $category_arr[0]['id_category'];
			}
			
	    }
	}
	
	foreach ($categories as $id => $data) {
	    echo "get category at link: ".$base_url.$data['url']."\n";
	    $client->get($base_url.$data['url']);
	    preg_match_all('#currentPage=([0-9])*#', $client->getBody(), $match);
	    $max_pager = max($match[1]);
	    
	    // go throught every page to take all products
	    
	    for ($current_page = 1; $current_page <= $max_pager; $current_page++) {
	        echo "  get page: ".$current_page."\n";
	        $client->get($base_url.$data['url'].'&currentPage='.$current_page);
	        $doc = new DOMDocument();
	        @$doc->loadHTML($client->getBody());
	        $xpath = new DOMXpath($doc);
	        $nodes = $xpath->query('//table[@id="ctl00_ContentPlaceHolder2_ctl02_ctl00_ctl00_dlProductList"]/tr');
	        foreach ($nodes as $node) {
	            $tds = $xpath->query('td/div/table/tr/td/div/a', $node);
	            foreach ($tds as $td) {
	                foreach ($td->attributes as $name => $attr_node) {
	                    if ($name == 'href') {
							$product_link = $attr_node->nodeValue;
	                    } else if ($name == 'title') {
							$product_name = $attr_node->nodeValue;
						}
					}
					
					$product = new Product(null, false, 6);
					$is_exist = false;
					
					// Check the existance of Product by name
					if (!$product->searchByNameOnly(6, $product_name))
						$product->name = pSQL($product_name);
					else
						$is_exist = true;

					if (!$is_exist)
					{
						$client->get($base_url.$product_link); // this is the link for each product
						// TODO: parse the code and put contents to database
						
						$doc2 = new DOMDocument();
						@$doc2->loadHTML($client->getBody());
						$xpath2 = new DOMXpath($doc2);
						
						$product->id_manufacturer = 3;
						$product->id_category_default = $data['prestashop_id'];
						$product->condition = 'new';
						$product->quantity = 1;
					
						$price_nodes = $xpath2->query('//*[@id="ctl00_ContentPlaceHolder2_ctl01_lblSalePrice"]');
						foreach ($price_nodes as $price)
						{
							$price_temp = preg_replace("/[^0-9]/i", "", $price->nodeValue);
							$price_temp = intval($price_temp);
							$product->price = $price_temp;
							break;
						}
						
						$reference_nodes = $xpath2->query('//*[@id="ctl00_ContentPlaceHolder2_uspRightTopInfo"]/table/tbody/tr[@class="country"]/td');
						foreach ($reference_nodes as $reference)
						{
							$product->reference = preg_replace("/[^0-9]/i", "", $reference->nodeValue);
							break;
						}
						
						$product->save();
						$product->addToCategories($data['prestashop_id']);
						
						$reduction_nodes = $xpath2->query('//*[@id="ctl00_ContentPlaceHolder2_ctl01_pnDisPrice"]/tr[@class="priceDC"]/td');
						foreach ($reduction_nodes as $reduction_node)
						{
							$product->on_sale = 1;
							$product->save();
							
							$reduction = $reduction_node->nodeValue;
							$reduction = strrchr($reduction, '(');
							$reduction = preg_replace("/[^0-9]/i", "", $reduction);
							$reduction = (int)$reduction / 100;
							
							$specificPrice = new SpecificPriceCore();
							$specificPrice->id_product = $product->id;
							$specificPrice->id_shop = 0;
							$specificPrice->id_currency = 0;
							$specificPrice->id_country = 0;
							$specificPrice->id_group = 0;
							$specificPrice->from_quantity = 1;
							$specificPrice->from = '0000-00-00 00:00:00';
							$specificPrice->to = '0000-00-00 00:00:00';
							$specificPrice->price = $product->price;
							$specificPrice->reduction = $reduction;
							$specificPrice->reduction_type = 'percentage';
							$specificPrice->save();
							
							break;
						}
						
						// Get Description
						$iframe_nodes = $xpath2->query('//*[@id="iframeDesc"]');
						$description = "";
						foreach ($iframe_nodes as $iframe)
						{
							foreach ($iframe->attributes as $iframe_attr)
							{
								if ($iframe_attr->nodeName == 'src')
								{
									$client->get($base_url."/Display/".($iframe_attr->nodeValue));
									
									$doc3 = new DOMDocument();
									@$doc3->loadHTML($client->getBody());
									
									$xpath3 = new DOMXpath($doc3);
									
									$description_nodes = $xpath3->query('//*[@id="uspProductDesc"]/div');
									foreach($description_nodes as $description_node)
									{
										$temp_dom = new DOMDocument();
										$temp_dom->appendChild($temp_dom->importNode($description_node,true));
										$description = $temp_dom->saveHTML();
										break;
									}
									break;
								}
							}
							break;
						}
						
						// Language
						foreach ($ids_lang as $index => $value) {
							Db::getInstance()->autoExecute(
								_DB_PREFIX_.'product_lang',
								array(
									'id_product'     => $product->id,
									'name' => $product->name,
									'description' => $description,
									'link_rewrite' => get_link($product->name)
								), 
								'UPDATE', 'id_product = '.($product->id).' AND id_lang = '.$value);
						}
						
						// Images
						$highestPosition = Image::getHighestPosition($product->id);
						$imagesTypes = ImageType::getImagesTypes('products');
						$types = array('.gif' => 'image/gif', '.jpeg' => 'image/jpeg', '.jpg' => 'image/jpg', '.png' => 'image/png');
						$image = new Image();
						$image->id_product = (int)$product->id;
						$image->position = ++$highestPosition;
						$image->cover = ($highestPosition == 1 ? true : false);
						if (!$image->add())
							echo "Can't add images for ".$id_product." \n";

						$new_path = $image->getPathForCreation();
						
						$image_nodes = $xpath2->query('//*[@id="ctl00_ContentPlaceHolder2_ctl00_imgMain_M"]');
						
						foreach ($image_nodes as $imageToUp)
						{
							foreach ($imageToUp->attributes as $name => $attr_node)
								if ($name == 'src') {
									$src_image = $attr_node->nodeValue;
									
									$ext = (substr($src_image, -4) == 'jpeg') ? '.jpeg' : substr($src_image, -4);
									$type = (isset($types[$ext]) ? $types[$ext] : '');
									$dirDefault = dirname(dirname(__FILE__));
									$client2 = new WebFormClient();
									$client2->get($base_url.$src_image);
									file_put_contents($dirDefault."/temp.jpg", $client2->getBody());
									
									if (!imageResize($dirDefault."/temp.jpg", $new_path.'.'.$image->image_format))
									{
										$image->delete();
										throw new Exception('An error occurred while resizing image.');
									}
									break;
								}
							break;
						}
						
						
						foreach ($imagesTypes AS $k => $imageType)
							if (!imageResize($image->getPathForCreation().'.jpg', $image->getPathForCreation().'-'.stripslashes($imageType['name']).'.jpg', $imageType['width'], $imageType['height']))
							{
								$image->delete();
								throw new Exception(Tools::displayError('An error occurred while copying image.').' '.stripslashes($imageType['name']));
							}
					}
					
				}
	        }
	    }
	}
	
	function UNI_2_TXT ( $text )
	{
		$UNI	= array ( "á","à","ả","ã","ạ","ắ","ằ","ẳ","ẵ","ặ","ấ","ầ","ẩ","ẫ","ậ","é","è","ẻ","ẽ","ẹ","ế","ề","ể","ễ","ệ","í","ì","ỉ","ĩ","ị","ó","ò","ỏ","õ","ọ","ố","ồ","ổ","ỗ","ộ","ớ","ờ","ở","ỡ","ợ","ú","ù","ủ","ũ","ụ","ứ","ừ","ử","ữ","ự","ý","ỳ","ỷ","ỹ","ỵ","Á","À","Ả","Ã","Ạ","Ắ","Ằ","Ẳ","Ẵ","Ặ","Ấ","Ầ","Ẩ","Ẫ","Ậ","É","È","Ẻ","Ẽ","Ẹ","Ế","Ề","Ể","Ễ","Ệ","Í","Ì","Ỉ","Ĩ","Ị","Ó","Ỏ","Õ","Ọ","Ố","Ồ","Ổ","Ỗ","Ộ","Ơ","Ớ","Ờ","Ở","Ỡ","Ợ","Ú","Ù","Ủ","Ũ","Ụ","Ứ","Ừ","Ử","Ữ","Ự","Ý","Ỳ","Ỷ","Ỹ","Ỵ","ă","â","ê","ô","ơ","ư","đ","Ă","Â","Ê","Ô","Ò","Ư","Đ");
		$TXT	= array ( "a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","e","e","e","e","e","e","e","e","e","e","i","i","i","i","i","o","o","o","o","o","o","o","o","o","o","o","o","o","o","o","u","u","u","u","u","u","u","u","u","u","y","y","y","y","y","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","E","E","E","E","E","E","E","E","E","E","I","I","I","I","I","O","O","O","O","O","O","O","O","O","O","O","O","O","O","O","U","U","U","U","U","U","U","U","U","U","Y","Y","Y","Y","Y","a","a","e","o","o","u","d","A","A","E","O","O","U","D");
	
		for ($i = 0; $i < count($UNI); $i++)
		{
			$text = str_replace($UNI[$i], $TXT[$i], $text);
		}
		return $text;
	}
	
	function get_link($txt)
	{
		$text	=	UNI_2_TXT($txt);
		$text	=	strtolower($text);
		$text	=	str_replace("-", "", $text);
		$text	=	str_replace(" ", "-", $text);
		$text	=	str_replace("_", "-", $text);
		$src	=	array ( "?", "." , "," , "\"", "'", ":", "%", "/", "&", "[", "]", "+");
		for ($i = 0; $i < count($src); $i++)
			$text	=	str_replace($src[$i], "", $text);
		$text	=	str_replace("--", "-", $text);
		$text	=	str_replace("---", "-", $text);
		return $text;
	}
	
	function getFileName($path)
	{
		$parts=pathinfo($path);
		return $parts['basename'];
	}
?>